package Model;

import java.util.ArrayList;

/**
 * Manages bookings and aggregates them.
 * @author Yury Kitaev
 *
 */
public class BookingManager 
{
	private ArrayList<Booking> bookings;
	private Catalog catalog;
	
	public BookingManager(Catalog catalog)
	{
		super();
		this.catalog = catalog;
		bookings = new ArrayList<Booking>();
	}

	public Booking makeBooking(Person person, int id, int seatNumber) throws Service.EventClosedException
	{
		// Find event in the catalog
		Event event = null;
		for (Event e : catalog.getEvents())
		{
			if (e.getId() == id)
			{
				event = e;		
				break;
			}
		}
		
		if (null == event
		 || EventStatus.Closed == event.getStatus())
		{
			throw new Service.EventClosedException("The event is closed.");			
		}
		
		// Find a seat
		Seat seat = null;
		if (!event.getVenue().getSeats().get(seatNumber - 1).isTaken())
		{
			seat = event.getVenue().getSeats().get(seatNumber - 1);
		}
		else
		{
			// The seat was taken, take any available seat
			for (Seat s : event.getVenue().getSeats())
			{
				if (!s.isTaken())
				{
					seat = s;
				}
			}
		}
		if (null == seat)
		{
			throw new Service.EventClosedException("No seats found, the event must be closed!");
		}
		
		Booking booking = new Booking(person, event, seat);
		
		bookings.add(booking);
		
		event.refreshStatus();
		
		return booking;
	}
	
	/**
	 * Gets the list of bookings made
	 * @return
	 */
	public ArrayList<Booking> getBookings() 
	{
		return bookings;
	}

	public void setBookings(ArrayList<Booking> bookings) 
	{
		this.bookings = bookings;
	}

	public Catalog getCatalog() 
	{
		return catalog;
	}

	public void setCatalog(Catalog catalog) 
	{
		this.catalog = catalog;
	}
}
